package com.zx.controller;

import com.zx.common.ResponseCode;
import com.zx.entity.Food;
import com.zx.entity.News;
import com.zx.entity.Notice;
import com.zx.entity.User;
import com.zx.repository.NewsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
@RequestMapping("/news")
public class NewsController {

    @Autowired
    private NewsRepository newsRepository;

    @GetMapping("/list")
    public ModelAndView list(@RequestParam(value = "page", defaultValue = "0") Integer page,
                             @RequestParam(value = "size", defaultValue = "2") Integer size,
                             Map<String, Object> map) {
        PageRequest request = PageRequest.of(page, size);
        Page<News> news = newsRepository.findAll(request);
        map.put("news", news);
        return new ModelAndView("news/list", map);
    }
    //添加资讯
    @GetMapping("/addnews")
    public ModelAndView addnews() {
        return new ModelAndView("news/addNews");
    }
    //保存资讯
    @PostMapping("saveNews")
    public ModelAndView saveNews(News news,
                                 Map<String, Object> map) {
        newsRepository.save(news);
        map.put("msg", ResponseCode.SAVE_SUCCESS.getDesc());
        map.put("url", "/foodshare/news/list");
        return new ModelAndView("common/success", map);
    }
    //删除资讯
    @GetMapping("/delete/{newsId}")
    public ModelAndView delete(@PathVariable("newsId") Integer id,
                               Map<String,Object> map){
        News news = newsRepository.getOne(id);
        newsRepository.delete(news);
        map.put("msg",ResponseCode.DELETE_SUCCESS.getDesc());
        map.put("url","/foodshare/news/list");
        return new ModelAndView("common/success",map);
    }
    //编辑资讯
    @GetMapping("/list/{newsId}")
    public ModelAndView EditUser(@PathVariable("newsId") Integer id,
                                 Map<String,Object> map){
        News news = newsRepository.getOne(id);
        map.put("news",news);
        return new ModelAndView("news/editNews",map);
    }
}
